/**   
* @Title: StockController.java 
* @Package com.txby.platformApi.component.web 
* @Description: TODO(用一句话描述该文件做什么) 
* @author Administrator
* @date 2017年11月2日 下午4:07:49 
* @version V1.0   
*/
package com.txby.platformApi.component.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.jck.common.util.BeanToMapUtil;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.txby.pf.common.utils.PageUtils;
import com.txby.pf.common.utils.Query;
import com.txby.pf.common.utils.R;
import com.txby.pf.common.validator.ValidatorUtils;
import com.txby.pf.common.validator.group.AddGroup;
import com.txby.platformCore.entity.SysStockIn;

/** 
* @ClassName: StockController 
* @Description: 库存管理类 
* @author Administrator
* @date 2017年11月2日 下午4:07:49 
*  
*/
@RestController
@RequestMapping("/pro/stockIn")
public class StockInController extends CommonController {

	
	@RequestMapping("/list")
	@RequiresPermissions("pro:stockIn:info")
	public R list(@RequestParam Map<String, Object> params){
		String sql="SELECT si.status,si.stockStatus,si.deviceSN,si.materialCode,si.typeNo,si.stockInOper,si.deptId,si.remarks,si.stockInTime,si.updateTime,s.brand,s.deviceName,s.specification,u.username stockInOperName,d.name deptName "
					+"FROM t_txby_sys_stockIn si LEFT JOIN t_txby_sys_stock s "
					+" on si.materialCode=s.materialCode and si.deviceType=s.deviceType "
					+" left join sys_user u on u.user_id=si.stockInOper "
					+" left join sys_dept d on d.dept_id=si.deptId "
					+" where si.status=0 and si.stockStatus=2 ";
		String deviceName=params.get("deviceName")==null?"":params.get("deviceName").toString();
		if(!ChkUtil.isEmptyAllObject(deviceName)){
			if (deviceName.contains("%") || deviceName.contains("_")) {
				deviceName = deviceName.trim().replace("%", "\\%").replace("_", "\\_");
				deviceName = "%" + deviceName + "%";
				sql += " and t.deviceName like #{pojo.deviceName} escape '\\'";
				params.put("deviceName", "%" + deviceName.trim() + "%");
			} else {
				deviceName = "%" + deviceName.trim() + "%";
				sql += " and t.deviceName like #{pojo.deviceName} ";
				params.put("deviceName", "%" + deviceName.trim() + "%");
			}
		}
		sql += Query.getLastSortSql(params, " order by updateTime ");
		//查询列表数据
		PageList<Map> pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, Query.getPageBean(params), params);
		PageUtils pageUtil = new PageUtils(pl.getResultList(), pl.getPageBean().getTotalCount().intValue(),  pl.getPageBean().getPageSize(), pl.getPageBean().getPage());
		return R.ok().put("page", pageUtil);
	}
	/**
	 * 
	* @Title: list 
	* @Description: 获取待入库的deviceSN列表
	* @param @param params
	* @param @return    设定文件 
	* @return R    返回类型 
	* @throws
	 */
	@RequestMapping("/queryDeviceSNList")
	@RequiresPermissions("pro:stockIn:info")
	public R queryDeviceSNList(@RequestParam Map<String, Object> params){
		String sql="SELECT t.deviceSN value,t.deviceSN text FROM  "+this.mBaseDao.tableName(SysStockIn.class)+" t WHERE deviceType='pd' and stockStatus=1 and status=0" ;
		List typeList=mBaseDao.findBySql(sql, Map.class, null);
		return R.ok().put("sns", typeList);
	}
	
 
	
	/**
	 * 查询信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("pro:stockIn:info")
	public R info(@PathVariable("id") String id){
		String sql="SELECT t.*  FROM  "+this.mBaseDao.tableName(SysStockIn.class)+" t WHERE  t.id='"+id+"'" ;
		Map stock =  (Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, null);
		return R.ok().put("stock", stock);
	}
	
	/**
	 * 保存库存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("pro:stockIn:save")
	public R save(@RequestBody SysStockIn stockIn){
		try {
			ValidatorUtils.validateEntity(stockIn);
			if(StringUtils.isEmpty(stockIn.getDeviceSN())) {
				return R.ok().error("设备SN不能为空");
			}
			String sql="";
			if("pd".equalsIgnoreCase(stockIn.getDeviceType())) {
				List<String> list = JSONArray.parseArray(stockIn.getDeviceSN(),String.class);
				String[] o = list.toArray(new String[list.size()]);
				String sns=StringUtils.join(o, ",");
				sql="select * from "+this.mBaseDao.tableName(SysStockIn.class)+" where typeNo='"+stockIn.getTypeNo()+"'";
				SysStockIn old=(SysStockIn) this.mBaseDao.findBySqlUniqueObject(sql, SysStockIn.class, null);
				 if(old!=null){
					 return R.ok().error("该类型的设备型号重复");
				 }
				 stockIn.setCreater(getUserId().toString());
				 stockIn.setUpdater(getUserId().toString());
				 stockIn.setStockInOper(getUserId().toString());
				 sql="update t_txby_sys_stockIn set stockStatus=2,deviceType=#{pojo.deviceType},typeNo=#{pojo.typeNo},stockInOper=#{pojo.stockInOper}"
				 		+ ",materialCode=#{pojo.materialCode},stockInTime=NOW(),createTime=now(),updateTime=now(),creater=#{pojo.creater},updater=#{pojo.updater},deptId=#{pojo.deptId},remarks=#{pojo.remarks} where deviceSN in ("
				 		+sns+")";
				 Map m = new HashMap();
				 m=BeanToMapUtil.convertBean(stockIn);
				 this.mBaseDao.executeSql(sql, m);
			} else {
				 stockIn.setCreater(getUserId().toString());
				 stockIn.setUpdater(getUserId().toString());
				 stockIn.setStockInOper(getUserId().toString());
				stockIn.setStockStatus(2);
				stockIn.setStatus(0);
				stockIn.setStockInTime(new Date());
				mBaseDao.saveObject(stockIn);
			}

		} catch (Exception e) {
			return R.error(5000,e.getMessage());
		}
		return R.ok();
	}
	
	/**
	 * 修改库存
	 */
	@RequestMapping("/update")
	@RequiresPermissions("pro:stockIn:update")
	public R update(@RequestBody  SysStockIn stock){
		try {
			ValidatorUtils.validateEntity(stock, AddGroup.class);
			String sql="select * from "+this.mBaseDao.tableName(SysStockIn.class)+" where typeNo ="+stock.getTypeNo()+" and id_!="+stock.getId_()+" ";
			SysStockIn old=(SysStockIn) this.mBaseDao.findBySqlUniqueObject(sql, SysStockIn.class, null);
			if(old!=null){
				return R.ok().error("该类型的设备型号重复");
			}else{
				old=(SysStockIn) this.mBaseDao.findBySqlUniqueObject("select * from "+this.mBaseDao.tableName(SysStockIn.class)+" where   id_="+stock.getId_(), SysStockIn.class, null);
				if(old!=null){
					this.mBaseDao.updateObject(stock);
				}
			}
			
		}catch (Exception e) {
			return R.error(5000,e.getMessage());
		}
		return R.ok();
	}
	
	
	/**
	 * 删除库存
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("pro:stockIn:delete")
	public R delete(@RequestBody String[] ids){
		 for(String id:ids){
		    	this.mBaseDao.executeSql("update "+this.mBaseDao.tableName(SysStockIn.class)+" set status=0 where id='"+id+"'", null);
		  }
		return R.ok();
	}
}
